#!/bin/bash
# ES Archive Docker 构建脚本 - 支持多种镜像源

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 镜像源配置
MIRRORS=(
    "aliyun"
    "tencent" 
    "huawei"
    "ustc"
    "tsinghua"
    "default"
)

# 获取镜像源配置
get_mirror_config() {
    local mirror=$1
    
    case $mirror in
        "aliyun")
            echo "阿里云镜像源"
            APT_MIRROR="mirrors.aliyun.com"
            PIP_INDEX="https://mirrors.aliyun.com/pypi/simple/"
            PIP_HOST="mirrors.aliyun.com"
            ;;
        "tencent")
            echo "腾讯云镜像源"
            APT_MIRROR="mirrors.tencent.com"
            PIP_INDEX="https://mirrors.tencent.com/pypi/simple/"
            PIP_HOST="mirrors.tencent.com"
            ;;
        "huawei")
            echo "华为云镜像源"
            APT_MIRROR="mirrors.huaweicloud.com"
            PIP_INDEX="https://mirrors.huaweicloud.com/pypi/simple/"
            PIP_HOST="mirrors.huaweicloud.com"
            ;;
        "ustc")
            echo "中科大镜像源"
            APT_MIRROR="mirrors.ustc.edu.cn"
            PIP_INDEX="https://mirrors.ustc.edu.cn/pypi/simple/"
            PIP_HOST="mirrors.ustc.edu.cn"
            ;;
        "tsinghua")
            echo "清华大学镜像源"
            APT_MIRROR="mirrors.tuna.tsinghua.edu.cn"
            PIP_INDEX="https://pypi.tuna.tsinghua.edu.cn/simple/"
            PIP_HOST="pypi.tuna.tsinghua.edu.cn"
            ;;
        "default"|*)
            echo "官方镜像源"
            APT_MIRROR=""
            PIP_INDEX=""
            PIP_HOST=""
            ;;
    esac
}

# 生成 Dockerfile
generate_dockerfile() {
    local mirror=$1
    local dockerfile_name="Dockerfile.es-archive"
    
    if [ "$mirror" != "default" ]; then
        dockerfile_name="Dockerfile.es-archive.${mirror}"
    fi
    
    get_mirror_config $mirror
    
    print_message $BLUE "生成 Dockerfile: $dockerfile_name"
    print_message $YELLOW "使用镜像源: $(get_mirror_config $mirror)"
    
    cat > $dockerfile_name << EOF
# ES Archive Dockerfile - $(get_mirror_config $mirror)
FROM python:3.11-slim

# 设置工作目录
WORKDIR /app

# 设置构建参数
ARG MIRROR_TYPE=${mirror}
ARG BUILD_DATE
ARG VERSION

# 添加标签
LABEL maintainer="ES Archive Team" \\
      version="\${VERSION}" \\
      build-date="\${BUILD_DATE}" \\
      mirror="\${MIRROR_TYPE}"

EOF

    if [ "$mirror" != "default" ]; then
        cat >> $dockerfile_name << EOF
# 配置 ${mirror} 镜像源
RUN sed -i 's/deb.debian.org/${APT_MIRROR}/g' /etc/apt/sources.list.d/debian.sources && \\
    sed -i 's/security.debian.org/${APT_MIRROR}/g' /etc/apt/sources.list.d/debian.sources

# 配置 APT 忽略 GPG 签名验证（解决镜像源签名问题）
RUN echo 'Acquire::Check-Valid-Until "false";' > /etc/apt/apt.conf.d/99ignore-release-date && \\
    echo 'Acquire::AllowInsecureRepositories "true";' >> /etc/apt/apt.conf.d/99ignore-release-date && \\
    echo 'Acquire::AllowDowngradeToInsecureRepositories "true";' >> /etc/apt/apt.conf.d/99ignore-release-date && \\
    echo 'APT::Get::AllowUnauthenticated "true";' >> /etc/apt/apt.conf.d/99ignore-release-date

# 配置 pip ${mirror} 镜像
RUN mkdir -p /root/.pip && \\
    echo '[global]' > /root/.pip/pip.conf && \\
    echo 'index-url = ${PIP_INDEX}' >> /root/.pip/pip.conf && \\
    echo 'trusted-host = ${PIP_HOST}' >> /root/.pip/pip.conf

EOF
    fi

    cat >> $dockerfile_name << 'EOF'
# 安装最小系统依赖（减少构建时间）
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# 安装 uv（Python 包管理器）
RUN pip install --no-cache-dir uv

EOF

    if [ "$mirror" != "default" ]; then
        cat >> $dockerfile_name << EOF
# 配置 uv 使用 ${mirror} 镜像
ENV UV_INDEX_URL=${PIP_INDEX}
ENV UV_TRUSTED_HOST=${PIP_HOST}

EOF
    fi

    cat >> $dockerfile_name << 'EOF'
# 复制项目结构文件
COPY pyproject.toml uv.lock* README.md ./
COPY src/ ./src/

# 安装 Python 依赖（分层缓存优化）
RUN uv pip install --system -e . --no-cache-dir

# 复制其余项目文件
COPY . .

# 创建必要的目录
RUN mkdir -p /data/backups /data/metadata /data/logs /app/config

# 复制默认配置文件
COPY config/docker-config-minimal.yaml /app/config/default.yaml

# 设置环境变量
ENV PYTHONPATH=/app/src

# 创建非 root 用户
USER root

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD es-archive --help || exit 1

# 默认命令
CMD ["es-archive", "--help"]
EOF

    print_message $GREEN "✓ Dockerfile 生成完成: $dockerfile_name"
}

# 构建镜像
build_image() {
    local mirror=$1
    local tag=${2:-latest}
    local dockerfile_name="Dockerfile.es-archive"
    
    if [ "$mirror" != "default" ]; then
        dockerfile_name="Dockerfile.es-archive.${mirror}"
    fi
    
    local image_name="es-archive:${tag}-${mirror}"
    
    print_message $BLUE "构建镜像: $image_name"
    print_message $YELLOW "使用 Dockerfile: $dockerfile_name"
    
    # 构建参数
    local build_args=(
        --build-arg "MIRROR_TYPE=${mirror}"
        --build-arg "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
        --build-arg "VERSION=${tag}"
        --tag "$image_name"
        --file "$dockerfile_name"
    )
    
    # 执行构建
    docker build "${build_args[@]}" .
    
    if [ $? -eq 0 ]; then
        print_message $GREEN "✓ 镜像构建成功: $image_name"
        
        # 创建别名
        if [ "$mirror" = "aliyun" ]; then
            docker tag "$image_name" "es-archive:${tag}"
            print_message $GREEN "✓ 创建别名: es-archive:${tag}"
        fi
    else
        print_message $RED "✗ 镜像构建失败"
        return 1
    fi
}

# 测试镜像
test_image() {
    local mirror=$1
    local tag=${2:-latest}
    local image_name="es-archive:${tag}-${mirror}"
    
    print_message $BLUE "测试镜像: $image_name"
    
    # 测试镜像是否能正常运行
    if docker run --rm "$image_name" es-archive --version > /dev/null 2>&1; then
        print_message $GREEN "✓ 镜像测试通过"
    else
        print_message $RED "✗ 镜像测试失败"
        return 1
    fi
}

# 清理临时文件
cleanup() {
    print_message $BLUE "清理临时文件..."
    
    for mirror in "${MIRRORS[@]}"; do
        if [ "$mirror" != "default" ] && [ -f "Dockerfile.es-archive.${mirror}" ]; then
            rm -f "Dockerfile.es-archive.${mirror}"
            print_message $YELLOW "删除: Dockerfile.es-archive.${mirror}"
        fi
    done
    
    print_message $GREEN "✓ 清理完成"
}

# 显示帮助
show_help() {
    echo "ES Archive Docker 构建脚本"
    echo ""
    echo "用法: $0 [选项] [镜像源]"
    echo ""
    echo "镜像源选项:"
    for mirror in "${MIRRORS[@]}"; do
        get_mirror_config $mirror > /dev/null
        echo "  $mirror - $(get_mirror_config $mirror)"
    done
    echo ""
    echo "选项:"
    echo "  -t, --tag TAG     指定镜像标签 (默认: latest)"
    echo "  -a, --all         构建所有镜像源版本"
    echo "  -c, --clean       构建后清理临时文件"
    echo "  -T, --test        构建后测试镜像"
    echo "  -h, --help        显示此帮助"
    echo ""
    echo "示例:"
    echo "  $0 aliyun                    # 使用阿里云镜像源构建"
    echo "  $0 -t v1.0 aliyun          # 构建指定标签版本"
    echo "  $0 -a -c                   # 构建所有版本并清理"
    echo "  $0 -T aliyun               # 构建并测试"
}

# 主函数
main() {
    local mirror="aliyun"  # 默认使用阿里云镜像
    local tag="latest"
    local build_all=false
    local clean_after=false
    local test_after=false
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -t|--tag)
                tag="$2"
                shift 2
                ;;
            -a|--all)
                build_all=true
                shift
                ;;
            -c|--clean)
                clean_after=true
                shift
                ;;
            -T|--test)
                test_after=true
                shift
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            -*)
                print_message $RED "未知选项: $1"
                show_help
                exit 1
                ;;
            *)
                mirror="$1"
                shift
                ;;
        esac
    done
    
    # 验证镜像源
    if [ "$build_all" = false ]; then
        local valid_mirror=false
        for m in "${MIRRORS[@]}"; do
            if [ "$m" = "$mirror" ]; then
                valid_mirror=true
                break
            fi
        done
        
        if [ "$valid_mirror" = false ]; then
            print_message $RED "无效的镜像源: $mirror"
            print_message $YELLOW "可用的镜像源: ${MIRRORS[*]}"
            exit 1
        fi
    fi
    
    print_message $BLUE "ES Archive Docker 构建脚本"
    print_message $BLUE "=========================="
    
    if [ "$build_all" = true ]; then
        print_message $BLUE "构建所有镜像源版本..."
        
        for m in "${MIRRORS[@]}"; do
            print_message $BLUE "\n--- 构建 $m 版本 ---"
            generate_dockerfile "$m"
            build_image "$m" "$tag"
            
            if [ "$test_after" = true ]; then
                test_image "$m" "$tag"
            fi
        done
    else
        generate_dockerfile "$mirror"
        build_image "$mirror" "$tag"
        
        if [ "$test_after" = true ]; then
            test_image "$mirror" "$tag"
        fi
    fi
    
    if [ "$clean_after" = true ]; then
        cleanup
    fi
    
    print_message $GREEN "\n🎉 构建完成！"
    
    # 显示构建的镜像
    print_message $BLUE "\n构建的镜像:"
    if [ "$build_all" = true ]; then
        for m in "${MIRRORS[@]}"; do
            echo "  es-archive:${tag}-${m}"
        done
    else
        echo "  es-archive:${tag}-${mirror}"
        if [ "$mirror" = "aliyun" ]; then
            echo "  es-archive:${tag} (别名)"
        fi
    fi
}

# 错误处理
trap 'print_message $RED "构建失败！"; cleanup; exit 1' ERR

# 运行主函数
main "$@"
